import React, { useEffect, useState } from 'react';
import { Form, Input, InputNumber, Select, message, Upload, Button } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import ContentTitle from "@/components/contentTitle/ContentTitle";
import { getGoodsType, addGoods } from '@/api/goods';
import { useNavigate } from 'react-router-dom';
import { baseUrl } from "@/utile/commen.js";

const GoodsAdd = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [types, setTypes] = useState([
    {
      key: '1',
      label: '',
      value: ''
    }
  ])
  const [imgUrl, setImgUrl] = useState('');
  const [loading, setLoading] = useState(false);

  // 分类获取部分
  const getTypes = async () => {
    const { categories } = await getGoodsType();
    const newData = categories.map((item, index) => {
      return {
        label: item.cateName,
        value: item.cateName,
        key: index
      }
    })
    setTypes(newData)
  }

  useEffect(() => {
    getTypes();
  }, [])

  // 图片上传处理
  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      setImgUrl(info.file.response.imgUrl);
      setLoading(false);
      message.success('图片上传成功');
    }
    if (info.file.status === 'error') {
      setLoading(false);
      message.error('图片上传失败');
    }
  };

  // 提交表单
  const onFinish = async (values) => {
    console.log('表单数据:', values);
    // 处理图片路径
    const index = values.imgUrl[0].response.imgUrl.lastIndexOf('/');
    const processedImgUrl = values.imgUrl[0].response.imgUrl.slice(index + 1);
    console.log(processedImgUrl);
    const { code, msg } = await addGoods({
      ...values,
      imgUrl: processedImgUrl
    });


    if (code === 0) {
      message.success(msg);
      form.resetFields();
      setImgUrl('');
      navigate('/home/goodsList');
    } else {
      message.error(msg);
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传图片</div>
    </div>
  );

  return (
    <div>
      <ContentTitle title="商品添加" />
      <Form
        style={{marginTop: 20}}
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="商品名称"
          name="name"
        >
          <Input placeholder="请输入商品名称" />
        </Form.Item>

        <Form.Item
          label="商品分类"
          name="category"

        >
          <Select
            options={types}
            placeholder="请选择商品分类"
            optionFilterProp="label"
          />
        </Form.Item>

        <Form.Item
          label="商品价格"
          name="price"
        >
          <InputNumber min={0} placeholder="请输入价格" />
        </Form.Item>

        <Form.Item
          label="商品图片"
          name="imgUrl"
          valuePropName="fileList"
          getValueFromEvent={(e) => e.fileList}
        >
          <Upload
            // name="imgUrl" 不要加名字 否则会与nodejs 中的name冲突
            listType="picture-card"
            showUploadList={false}
            action="/poo/goods/goods_img_upload"
            beforeUpload={beforeUpload}
            onChange={handleChange}
            headers={{
              Authorization: `Bearer ${JSON.parse(sessionStorage.getItem('user')).token}`
            }}
          >
            {imgUrl ? (
              <img src={baseUrl + imgUrl} alt="商品图片" style={{ width: '100%' }} />
            ) : uploadButton}
          </Upload>
        </Form.Item>

        <Form.Item
          label="商品描述"
          name="goodsDesc"

        >
          <Input.TextArea rows={4} />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 4 }}>
          <Button type="primary" htmlType="submit" size="large">
            添加商品
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

// 图片上传校验
const beforeUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png'].includes(file.type);
  if (!isImage) message.error('只能上传 JPG/PNG 格式!');

  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) message.error('图片大小不能超过 2MB!');

  return isImage && isLt2M;
};

export default GoodsAdd;